package com.heima.common.baiduyun.utils;

import com.baidu.aip.contentcensor.AipContentCensor;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * ClassName: textExamine
 * Description: 百度云内容审核工具类
 * date: 2023/8/10 0010 16:07
 *
 * @author zHan
 */

@Getter
@Setter
@Component
@ConfigurationProperties(prefix = "baiduyun")
@Slf4j
public class ExamineUtil {

    private String appID;
    private String apiKey;
    private String secretKey;

    /**
     * 图片审核
     * @param file 图片字节
     * @return
     */
    public Map imgExamine(byte[] file) {
        Map<String, Object> map = new HashMap<>();
        AipContentCensor client = new AipContentCensor(appID, apiKey, secretKey);
        JSONObject jsonObject = client.imageCensorUserDefined(file,null);
        log.info(String.valueOf(jsonObject));
        // 解析数据
        return analyzeData(map, jsonObject);
    }

    /**
     * 文本审核
     * @param text 文本内容
     * @return
     */
    public Map textExamine(String text) {
        Map<String, Object> map = new HashMap<>();
        AipContentCensor client = new AipContentCensor(appID, apiKey, secretKey);
        JSONObject jsonObject = client.textCensorUserDefined(text);
        log.info(String.valueOf(jsonObject));
        // 解析数据
        return analyzeData(map, jsonObject);
    }

    /**
     * 解析数据
     * @param map
     * @param jsonObject
     * @return
     */
    private Map<String, Object> analyzeData(Map<String, Object> map, JSONObject jsonObject) {
        // conclusionType,1:合规；2:不合规；3:疑似，需要人工审核；4:审核失败
        int conclusionType = jsonObject.getInt("conclusionType");
        if (conclusionType==1) {
            map.put("code", "pass");
        } else if (conclusionType==2) {
            map.put("code", "block");
            JSONArray data = jsonObject.getJSONArray("data");
            map.put("data", data);
        } else if (conclusionType==3) {
            map.put("code", "suspected");
        } else {
            map.put("code", "error");
        }
        return map;
    }
}
